/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY. 
 * See the GNU General Public License for more details.
 * 
 * Copyright (C) 2011 CellObject.net
 */
package net.cellobject.javacodeformatter.model;

import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;

public class FormatterResource implements IFormatterItem {
	private final FormatterItemType type;

	private final IResource resource;

	private String name;

	FormatterResource(final FormatterItemType type, final IResource resource) {
		this.type = type;
		this.resource = resource;
	}

	public static FormatterResource loadFavorite(final FormatterItemType type, final String info) {
		final IResource res = ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(info));
		if (res == null) {
			return null;
		}
		return new FormatterResource(type, res);
	}

	public String getName() {
		if (name == null) {
			name = resource.getName();
		}
		return name;
	}

	public void setName(final String newName) {
		name = newName;
	}

	public String getLocation() {
		final IPath path = resource.getLocation().removeLastSegments(1);
		if (path.segmentCount() == 0) {
			return "";
		}
		return path.toString();
	}

	public boolean isFavoriteFor(final Object obj) {
		return resource.equals(obj);
	}

	public FormatterItemType getType() {
		return type;
	}

	@Override
	public boolean equals(final Object obj) {
		return (this == obj) || ( (obj instanceof FormatterResource) && resource.equals( ((FormatterResource)obj).resource));
	}

	@Override
	public int hashCode() {
		return resource.hashCode();
	}

	// For now, this is how we suppress a warning that we cannot fix
	// See Bugzilla #163093 and Bugzilla #149805 comment #14
	@SuppressWarnings("rawtypes")
	public Object getAdapter(final Class adapter) {
		return getAdapterDelegate(adapter);
	}

	private Object getAdapterDelegate(final Class<?> adapter) {
		if (adapter.isInstance(resource)) {
			return resource;
		}
		return Platform.getAdapterManager().getAdapter(this, adapter);
	}

	public String getInfo() {
		return resource.getFullPath().toString();
	}
}
